package org.fanximall.erp.common.utils;

import com.google.common.base.VerifyException;
import org.apache.commons.lang3.ObjectUtils;

import java.util.function.Supplier;

/**
 * @author :  william
 * @version :  V1.0  created in 2024/4/22
 */
public class ExceptionUtils {


    /**
     * 如果throwEx为true，则抛出由exceptionSupplier提供的异常
     * @param throwEx 是否抛出异常
     * @param exceptionSupplier 提供异常的函数式接口
     * @param <X> 异常类型
     * @throws X 如果throwEx为true，则抛出该异常
     */
    public static <X extends Throwable> void ifTrueThrow(boolean throwEx, Supplier<? extends X> exceptionSupplier) throws X {
        if (throwEx) {
            throw exceptionSupplier.get();
        }
    }

    /**
     * 如果对象为空，则抛出由exceptionSupplier提供的异常
     * @param data 数据对象
     * @param exceptionSupplier 提供异常的函数式接口
     * @param <X> 异常类型
     * @throws X 如果throwEx为true，则抛出该异常
     */
    public static <X extends Throwable> void ifEmptyThrow(Object data, Supplier<? extends X> exceptionSupplier) throws X {
        if (ObjectUtils.isEmpty(data)) {
            throw exceptionSupplier.get();
        }
    }


    /**
     * 如果对象为空，则抛出校验异常
     * @param data 数据对象
     * @param message 异常信息
     */
    public static void ifEmptyThrowVerifyException(Object data,String message){
            ifEmptyThrow(data,()->new VerifyException(message));
    }


    /**
     * 如果throwEx为true，则抛出校验异常
     * @param throwEx 是否抛出异常
     * @param message 异常信息
     * @throws X 如果throwEx为true，则抛出该异常
     */
    public static <X extends Throwable> void ifTrueThrowVerifyException(boolean throwEx,String message) throws X {
        ifTrueThrow(throwEx,()->new VerifyException(message));
    }

}
